package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constans.message.WmNewsMessageConstants;
import com.heima.common.constans.wemedia.WemediaContans;
import com.heima.model.admin.dtos.NewsAuthDto;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.media.dtos.WmNewsDto;
import com.heima.model.media.dtos.WmNewsPageReqDto;
import com.heima.model.media.pojos.WmMaterial;
import com.heima.model.media.pojos.WmNews;
import com.heima.model.media.pojos.WmNewsMaterial;
import com.heima.model.media.pojos.WmUser;
import com.heima.model.media.vo.WmNewsVo;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmMaterialService;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.utils.ThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
    @Value("${fileServerUrl}")
    private  String fileServerUrl;
    @Autowired
    private KafkaTemplate kafkaTemplate;
    @Autowired
    private WmNewsMapper wmNewsMapper;
    @Autowired
    private WmUserMapper wmUserMapper;

    /**
     * 查询文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public PageResponseResult findList(NewsAuthDto dto) {
//1.检查参数
        dto.checkParam();
        //设置起始页
        dto.setPage((dto.getPage()-1)*dto.getSize());
        dto.setTitle("%"+dto.getTitle()+"%");

        //2.分页查询
        List<WmNewsVo> list = wmNewsMapper.findListAndPage(dto);
        //统计多少条数据
        int count = wmNewsMapper.findListCount(dto);

        //3.结果返回
        PageResponseResult responseResult = new PageResponseResult(dto.getPage(),dto.getSize(),count);
        responseResult.setData(list);
        return responseResult;
    }

    /**
     * 查询文章详情
     *
     * @param id
     * @return
     */
    @Override
    public WmNewsVo findWmNewsVo(Integer id) {
        //1.查询文章信息
        WmNews wmNews = getById(id);
        //2.查询作者
        WmUser wmUser = null;
        if(wmNews!=null && wmNews.getUserId() != null){
            wmUser = wmUserMapper.selectById(wmNews.getUserId());
        }

        //3.封装vo信息返回
        WmNewsVo wmNewsVo = new WmNewsVo();
        BeanUtils.copyProperties(wmNews,wmNewsVo);
        if(wmUser != null){
            wmNewsVo.setAuthorName(wmUser.getName());
        }
        return wmNewsVo;
    }

    /**
     * 查询需要发布的文章id列表
     *
     * @return
     */
    @Override
    public List<Integer> findRelease() {
        LambdaQueryWrapper<WmNews> query=new LambdaQueryWrapper<>();
        query.eq(WmNews::getStatus,8).lt(WmNews::getPublishTime,new Date());
        List<WmNews> list = list(query);
        List<Integer> integerList = list.stream().map(WmNews::getId).collect(Collectors.toList());
        return integerList;
    }

    /**
     * 提交文章
     *
     * @param dto
     * @param isSubmit 是否为提交 1 为提交 0为草稿
     * @return
     */
    @Override
    public ResponseResult saveNews(WmNewsDto dto, Short isSubmit) {
        WmNews wmNews = new WmNews();
        wmNews.setId(6237);
       /* //检查参数
        if (dto==null||dto.getContent()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        WmNews wmNews = new WmNews();
        wmNews.setImages(dto.getImages().toString());
        //复制内容到wmNews对象
        BeanUtils.copyProperties(dto,wmNews);
        // 获取内容中的素材
       List<String> imgList = fingImageInMain(dto);
        // 根据type来设置wmnews的images封面图片
        ResponseResult result = setImages4Type(wmNews,imgList);
        // 如果不等于null说明出错了
        if (result!=null) return result;
        // 文章保存或存为草稿
        saveWmNews(wmNews, isSubmit);
        // 关联文章中的图片到中间表
        saveReferenceImgAndarticle(wmNews,imgList);*/
        // 把newId发送给admin端的kafka
        kafkaTemplate.send("news-id", JSON.toJSONString(wmNews.getId()));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    private WmMaterialService wmMaterialService;
    @Autowired
    private WmNewsMaterialMapper wmNewsMaterialMapper;
    @Autowired
    private WmMaterialMapper wmMaterialMapper;
    /**
     * 保存中间表信息
     * @param wmNews
     * @param articleImgList 文章图片
     */
    private void saveReferenceImgAndarticle(WmNews wmNews, List<String> articleImgList) {
        if (wmNews.getId()!=null){
            // 修改文章的方法,先删除关系
            // 删除中间表的信息
            wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,wmNews.getId()));
        }
        // 当前登录用户id
        Integer userId = ThreadLocalUtils.getUser().getId();
        LambdaQueryWrapper<WmMaterial> wrapper = new LambdaQueryWrapper<>();
        if (wmNews.getType()!=0){
            // 封面图片不为无图,才查询封面图片的id
            String images = wmNews.getImages();
            String[] split = images.split(",");
            List<String> coverImageList = new ArrayList<>();
            for (String s : split) {
                coverImageList.add(s);
            }

            wrapper.eq(WmMaterial::getUserId,userId)
                    .in(WmMaterial::getUrl,coverImageList);
            List<WmMaterial> list = wmMaterialMapper.selectList(wrapper);
            List<Integer> coverImageIds = new ArrayList<>();
            list.forEach(item->{
                coverImageIds.add(item.getId());
            });

            wmNewsMaterialMapper.save4List(coverImageIds,wmNews.getId(),WemediaContans.WM_COVER_REFERENCE);
        }
        if (articleImgList.size()>0){
            // 查询文章内容的图片id
            wrapper.eq(WmMaterial::getUserId,userId)
                    .in(WmMaterial::getUrl,articleImgList);
            List<WmMaterial> list = wmMaterialMapper.selectList(wrapper);
            List<Integer> articleImageIds = new ArrayList<>();
            list.forEach(item->{
                articleImageIds.add(item.getId());
            });
            wmNewsMaterialMapper.save4List(articleImageIds,wmNews.getId(),WemediaContans.WM_CONTENT_REFERENCE);
        }



    }

    /**
     * 保存WmNews对象到数据库
     * @param wmNews 对象
     * @param isSubmit 状态
     */
    private void saveWmNews(WmNews wmNews, Short isSubmit) {
        if (isSubmit==1 ){
            //提交
            wmNews.setStatus(WmNews.Status.SUBMIT.getCode());
        }else {
            //草稿
            wmNews.setStatus(WmNews.Status.NORMAL.getCode());
        }
        Integer userId = ThreadLocalUtils.getUser().getId();
        wmNews.setUserId(userId);
        wmNews.setCreatedTime(new Date());
        wmNews.setSubmitedTime(new Date());
        // 更新还是新增文章
        if (wmNews.getId()==null){
            save(wmNews);
        }else {
            updateById(wmNews);
        }

    }

    /**
     * 获取文章主体中的图片
     * @param dto
     * @return
     */
    private List<String> fingImageInMain(WmNewsDto dto) {
        // 文章内容
        String content = dto.getContent();
        // 把文章内容转换成可识别的map
        List<Map> lists = JSON.parseArray(content, Map.class);
        // 要返回的图片的列表
        List<String> picList = new ArrayList<>();
        for (Map item : lists) {
            if ("image".equals(item.get("type"))){
                //获取图片中的链接
                picList.add(item.get("value").toString().replace(fileServerUrl,""));
            }
        }
        return picList;

    }


    /**
     * 给wmNews设置封面图片列表
     * @param wmNews 操作对象
     * @param imageList 图片列表
     */
    private ResponseResult setImages4Type(WmNews wmNews,List<String> imageList) {
        if (imageList==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
            // 前台传过来的文章类型
            Short type = wmNews.getType();
        // 类型是自动选择
            if (WemediaContans.WM_NEWS_TYPE_AUTO.equals(type)){
                //获取共有多少张图片
                int size = imageList.size();
                if (size==0){
                    wmNews.setType(WemediaContans.WM_NEWS_NONE_IMAGE);
                }else if (size<=2){
                    // 单图文章
                    wmNews.setType(WemediaContans.WM_NEWS_SINGLE_IMAGE);
                    wmNews.setImages(imageList.stream().limit(1).collect(Collectors.toList()).toString());
                } else{
                    // 多图文章
                    wmNews.setType(WemediaContans.WM_NEWS_MANY_IMAGE);
                   wmNews.setImages(imageList.stream().limit(3).collect(Collectors.toList()).toString());
                }

                String replace = wmNews.getImages().replaceAll(fileServerUrl, "").replace(" ", "").replace("[", "").replace("]", "");
                wmNews.setImages(replace);

            }else {
                if (type!=0){
                    String images = wmNews.getImages();
                   /* List<String> list = JSON.parseArray(images, String.class);
                    List<String> imgs = new ArrayList<>();
                    list.forEach(item->{
                        imgs.add(item.replace(fileServerUrl,""));

                });
                    String join = StringUtils.join(imgs);*/
                    String replace = images.replaceAll(fileServerUrl, "").replace(" ", "").replace("[", "").replace("]", "");
                    wmNews.setImages(replace);
                }
            }
        return null;

    }



    /**
     * 分页带条件查询自媒体文章列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findAll(WmNewsPageReqDto dto) {
        // 参数检查
        if (dto==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //查询条件
        LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
        // 设置文章状态
        if (dto.getStatus()!=null){
            wrapper.eq(WmNews::getStatus,dto.getStatus());
        }

        // 设置文章关键字
        if (dto.getKeyword()!=null){
            wrapper.like(WmNews::getTitle,dto.getKeyword());
        }
        // 设置频道列表
        if (dto.getChannelId()!=null){
            wrapper.eq(WmNews::getChannelId,dto.getChannelId());
        }
        // 设置文章发布日期区间
        if (dto.getBeginPubdate()!=null&&dto.getEndPubdate()!=null){
            wrapper.between(WmNews::getCreatedTime,dto.getBeginPubdate(),dto.getEndPubdate());
        }

        // 设置发布日期排序
        wrapper.orderByDesc(WmNews::getCreatedTime);
        //分页查询参数
        IPage<WmNews> ipage = new Page<>();
        ipage.setPages(dto.getPage());
        ipage.setSize(dto.getSize());
        IPage<WmNews> page = page(ipage,wrapper);
        ResponseResult result = new PageResponseResult(dto.getPage(),dto.getSize(),(int)page.getTotal());
        // 设置图片的host
        result.setHost(fileServerUrl);
        result.setData(page.getRecords());
        return result;
    }

    /**
     * 根据id查询文章
     *
     * @param id
     * @return
     */
    @Override
    public WmNews findById(Integer id) {
        WmNews one = getOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, id));
        return one;
      /*  //1.参数检查
        if(id == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章Id不可缺少");
        }

        if(one == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        ResponseResult r = ResponseResult.okResult(one);
        r.setHost(fileServerUrl);
        return r;*/
    }

    /**
     * 根据id删除文章
     *
     * @param id
     * @return
     */
    @Override
    public ResponseResult delById(Integer id) {
        if (id==null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"该操作需要文章ID");
        }
        // 先查询对象
        WmNews one = getOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, id));
        if(one == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        if (one.getType()==9||one.getEnable()==1){
            // 文章被使用,不能删除
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章已发布，不能删除");
        }
        // 删除中间表的信息
        wmNewsMaterialMapper.delete(Wrappers.<WmNewsMaterial>lambdaQuery().eq(WmNewsMaterial::getNewsId,one.getId()));
        // 删除new表数据
        //5.删除文章
        removeById(one.getId());
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 上架/下架文章
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateEnabledStatus(WmNewsDto dto) {
        //1.检查参数
        if(dto == null || dto.getId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 先查询对象
        WmNews one = getOne(Wrappers.<WmNews>lambdaQuery().eq(WmNews::getId, dto.getId()));
        if(one == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        if (one.getType()!=9){
            // 文章被使用,不能删除
            return ResponseResult.errorResult(666,"当前文章不可操作");
        }
//4.修改文章状态，同步到app端（后期做）TODO
        if(dto.getEnable() != null && dto.getEnable() > -1 && dto.getEnable() < 2){

            if(one.getArticleId()!=null){
                Map<String,Object> mesMap = new HashMap<>();
                mesMap.put("enable",dto.getEnable());
                mesMap.put("articleId",one.getArticleId());
                kafkaTemplate.send(WmNewsMessageConstants.WM_NEWS_UP_OR_DOWN_TOPIC,JSON.toJSONString(mesMap));
            }
        }
        update(Wrappers.<WmNews>lambdaUpdate().eq(WmNews::getId,dto.getId()).set(WmNews::getEnable,dto.getEnable()));
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
